﻿//string
//number
//boolean
//object
//array
//undefined
//function

//4 Function Invocation Patterns
//1. Apply/Call
//2. Function
//3. Method
//4. Object Constructor

var Car = function () {
    this.model = "Accord";
    this.make = "Honda";
};

var myCar = new Car();

var obj = {};
obj.name = "nick";
//AJAX
//HTTP - Hypertext Transfer Protocol

//HTTP Request
//Headers
//-URL: (http://mychatapp.firebaseio.com)
//-Verb/Method: GET, POST, DELETE, PUT, PATCH, OPTIONS
//Body
//JSON - JavaScript Object Notation


//HTTP Response
//Headers
//Body
// <html><head><title>Google</title></head><body><div></div>....

//https://chirptweet.firebaseio.com/

//AJAX - Asynchronous JavaScript and XML

 

//Object wrapper
var app = {};
//C.R.U.D.

app.displayTweets = function (response) {
    var resultDiv = document.getElementById('result');
    var tweets = JSON.parse(response);

    var h = '<ul>';

    for (var p in tweets) {
        var tweet = tweets[p].chirpTweet;
        if (typeof (tweet) != 'undefined') {
            h += '<li>' + tweet + '</li>';
        }
    }

    h += '</ul>';
    resultDiv.innerHTML = h;
}

//READ
app.getTweets = function (callback) {
    var request = new XMLHttpRequest();
    request.open("GET", "https://chirptweet.firebaseio.com/.json");
    request.onload = function () {
        //DOM - Document Object Model
        if (typeof (callback) == 'function') {
            callback(this.response);
        }
    };

    request.send();
}


//CREATE
app.createTweet = function () {
    var tweetInput = document.getElementById('chirp');

    var newTweet = {
        chirpTweet: tweetInput.value
    };

    tweetInput.value = '';

    var request = new XMLHttpRequest();
    request.open("POST", "https://chirptweet.firebaseio.com/.json");
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            app.getTweets(app.displayTweets);
        }
        //DOM - Document Object Model
        //var resultDiv = document.getElementById('result');
        //resultDiv.innerHTML = this.response;
    };
    
    request.send(JSON.stringify(newTweet));
}




app.getTweets(app.displayTweets);